package sg.techstudio.suntec.validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;

import sg.techstudio.suntec.filter.UserFilter;

@Component
public class UserFilterValidator {
	private static final Log log = LogFactory.getLog(UserFilterValidator.class);
	private static final String DELETE_EVENT = "delete";
	private static final String EDIT_EVENT = "edit";
	
	private static final String MSGARG_USER = "user(s)";
	
	public void validateList(UserFilter uf, ValidationContext context) {
		log.debug("validateList() entry");
		switch(context.getUserEvent()) {
		case DELETE_EVENT:
			validateCommonDelete(uf, context.getMessageContext());
			break;
		case EDIT_EVENT:
			validateCommonEdit(uf, context.getMessageContext());
			break;
		}
	}
	
	protected void validateCommonDelete(UserFilter uf, MessageContext messages) {
		log.debug("validateCommonDelete() entry");
		if(uf.getSelectedLength()<=0)
			messages.addMessage(new MessageBuilder().error().source("selectedContentIds")
					.code("selectcontent.delete").arg(MSGARG_USER).build());
	}
	
	protected void validateCommonEdit(UserFilter uf, MessageContext messages) {
		log.debug("validateCommonEdit() entry");
		if(uf.getSelectedLength()<=0)
			messages.addMessage(new MessageBuilder().error().source("selectedContentIds")
					.code("selectcontent.edit").arg(MSGARG_USER).build());
		else if(uf.getSelectedLength()>1)
			messages.addMessage(new MessageBuilder().error().source("selectedContentIds")
					.code("selectonecontent.edit").arg(MSGARG_USER).build());
	}

}
